// pages/search-results/search-results.ts
import { getPublishList } from '../../../api/publish.js'
import { 
  PAGE_PRODUCT_DETAIL, 
  PAGE_BULK_MATERIAL_DETAIL, 
  PAGE_DEMAND_DETAIL,
  PAGE_GROUP_DETAIL,
  goToPage 
} from '../../../config/pages.js'
import { formatSpecification } from '../../../utils/util'
import { formatDate } from '../../../utils/time'
import { getCategoryNames, getProductsByCategory, getDemandCategoryNames } from '../../../config/product-categories.js'

Page({
  data: {
    // 搜索关键词
    searchKeyword: '',
    
    // 筛选条件
    selectedProvince: '',
    selectedCity: '',
    selectedDistrict: '',
    filterActive: false,
    
    // 分类筛选
    selectedType: '', // 类型筛选（原求购分类位置）
    selectedProductCategory: '', // 产品类别（二级）
    selectedProductName: '', // 产品名称（三级）
    selectedCategoryText: '', // 显示的分类文本
    
    // 临时选择状态（用于弹窗中的选择）
    tempSelectedType: '', // 临时类型选择
    tempSelectedProductCategory: '', // 临时产品类别选择
    tempSelectedProductName: '', // 临时产品名称选择
    
    // 搜索结果
    resultList: [] as any[],
    filteredCount: 0,
    
    // 加载状态
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true,
    
    // 城市筛选弹窗
    showCityFilter: false,
    cityFilterValue: null as any,
    
    // 分类筛选弹窗
    showCategoryModalFlag: false,
    currentCategoryLevel: 'type', // type, category, product
    currentCategoryList: [] as string[],
    
    // 产品类别数据
    productCategoryList: getCategoryNames(), // 产品类别列表
    productNameList: [] as string[], // 产品名称列表（根据选择的产品类别动态加载）
    
    // 类型筛选数据
    typeList: [
      { value: 'group', label: '拼单' },
      { value: 'demand', label: '求购' },
      { value: 'processing', label: '加工' },
      { value: 'material', label: '材料' },
      { value: 'inventory', label: '散料' }
    ]
  },

  onLoad(options: any) {
    console.log('搜索结果页面加载完成', options);
    
    // 接收从 home 页面传递的搜索关键词
    if (options.keyword) {
      const keyword = decodeURIComponent(options.keyword);
      this.setData({
        searchKeyword: keyword
      });
      console.log('接收到的搜索关键词:', keyword);
    }
    
    this.loadSearchResults(true);
  },

  onShow() {
    console.log('搜索结果页面显示');
  },

  // 加载搜索结果数据
  async loadSearchResults(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        resultList: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加筛选条件
      if (this.data.selectedProvince) {
        params.province = this.data.selectedProvince;
      }
      if (this.data.selectedCity) {
        params.city = this.data.selectedCity;
      }
      if (this.data.selectedDistrict) {
        params.district = this.data.selectedDistrict;
      }
      
      // 添加分类筛选
      if (this.data.selectedType) {
        params.type = this.data.selectedType;
      }
      if (this.data.selectedProductCategory) {
        params.product_category = this.data.selectedProductCategory;
      }
      if (this.data.selectedProductName) {
        params.product_name = this.data.selectedProductName;
      }
      
      // 添加搜索关键词
      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword;
      }

      console.log('搜索参数:', params);
      const res = await getPublishList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化数据
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          spec: formatSpecification(item.spec || ''),
          formatted_date: formatDate(item.add_time || item.create_time),
          typeName: this.getTypeName(item.type),
          typeClass: this.getTypeClass(item.type)
        }));
        
        const newResults = refresh ? formattedList : [...this.data.resultList, ...formattedList];
        
        this.setData({
          resultList: newResults,
          filteredCount: res.data.count || newResults.length,
          hasMore: newResults.length < (res.data.count || 0),
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载搜索结果失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取类型名称
  getTypeName(type: string): string {
    const typeMap: any = {
      'group': '拼单',
      'demand': '求购',
      'processing': '加工',
      'material': '材料',
      'inventory': '散料'
    };
    return typeMap[type] || type;
  },

  // 获取类型样式类名
  getTypeClass(type: string): string {
    const classMap: any = {
      'group': 'group-order-item',
      'demand': 'demand-item',
      'processing': 'process-item',
      'material': 'material-item',
      'inventory': 'bulk-material-item'
    };
    return classMap[type] || 'material-item';
  },

  // 搜索输入处理
  onSearch(e: any) {
    const keyword = e.detail.value;
    console.log('搜索关键词:', keyword);
    this.setData({
      searchKeyword: keyword.trim()
    });
    this.loadSearchResults(true);
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.loadSearchResults(true);
  },

  // 筛选全国
  filterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false
    });
    this.loadSearchResults(true);
  },

  // 显示城市选择弹窗
  showCityModal() {
    this.setData({
      showCityFilter: true,
      cityFilterValue: {
        province: this.data.selectedProvince,
        city: this.data.selectedCity,
        district: this.data.selectedDistrict
      }
    });
  },

  // 城市筛选确认
  onCityFilterConfirm(e: any) {
    const { address } = e.detail;
    console.log('选择的城市:', address);
    
    this.setData({
      selectedProvince: address.province || '',
      selectedCity: address.city || '',
      selectedDistrict: address.district || '',
      filterActive: true,
      showCityFilter: false
    });
    
    this.loadSearchResults(true);
  },

  // 城市筛选取消
  onCityFilterCancel() {
    this.setData({
      showCityFilter: false
    });
  },

  // 清除城市筛选
  onCityFilterClear() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadSearchResults(true);
  },

  // 选择全国
  onCityFilterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadSearchResults(true);
  },

  // 显示分类筛选弹窗
  showCategoryModal() {
    this.setData({
      showCategoryModalFlag: true,
      currentCategoryLevel: 'type',
      // 初始化临时选择状态为当前已选择的值
      tempSelectedType: this.data.selectedType,
      tempSelectedProductCategory: this.data.selectedProductCategory,
      tempSelectedProductName: this.data.selectedProductName
    });
    this.loadCategoryList();
  },

  // 隐藏分类筛选弹窗
  hideCategoryModal() {
    this.setData({
      showCategoryModalFlag: false
    });
  },

  // 生成分类显示文本
  generateCategoryText(type: string, category: string, product: string) {
    const parts = [];
    if (type) {
      const typeItem = this.data.typeList.find(item => item.value === type);
      if (typeItem) parts.push(typeItem.label);
    }
    if (category) parts.push(category);
    if (product) parts.push(product);
    return parts.join('-');
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 切换分类级别
  switchCategoryLevel(e: any) {
    const level = e.currentTarget.dataset.level;
    this.setData({
      currentCategoryLevel: level
    });
    this.loadCategoryList();
  },

  // 加载分类列表
  loadCategoryList() {
    const { currentCategoryLevel, tempSelectedType, tempSelectedProductCategory } = this.data;
    let categoryList: string[] = [];

    if (currentCategoryLevel === 'type') {
      // 一级：类型筛选（拼单、求购、加工、材料、散料）
      categoryList = this.data.typeList.map(item => item.label);
    } else if (currentCategoryLevel === 'category' && tempSelectedType) {
      // 二级：产品类别（单面胶带、双面胶带等）
      categoryList = this.data.productCategoryList;
    } else if (currentCategoryLevel === 'product' && tempSelectedProductCategory) {
      // 三级：产品名称（根据产品类别获取）
      categoryList = getProductsByCategory(tempSelectedProductCategory);
    }

    this.setData({
      currentCategoryList: categoryList
    });
  },

  // 选择分类
  selectCategory(e: any) {
    const category = e.currentTarget.dataset.category;
    const { currentCategoryLevel } = this.data;

    if (currentCategoryLevel === 'category') {
      // 选择产品类别
      this.setData({
        tempSelectedProductCategory: category,
        tempSelectedProductName: ''
      });
      this.switchCategoryLevel({ currentTarget: { dataset: { level: 'product' } } });
    } else if (currentCategoryLevel === 'product') {
      // 选择产品名称
      this.setData({
        tempSelectedProductName: category
      });
    }
  },

  // 从分类弹窗中选择类型
  selectTypeFromCategory(e: any) {
    const type = e.currentTarget.dataset.type;
    
    this.setData({
      tempSelectedType: type,
      tempSelectedProductCategory: '',
      tempSelectedProductName: ''
    });
    this.switchCategoryLevel({ currentTarget: { dataset: { level: 'category' } } });
  },

  // 清除分类筛选
  clearCategoryFilter() {
    this.setData({
      selectedType: '',
      selectedProductCategory: '',
      selectedProductName: '',
      selectedCategoryText: '',
      tempSelectedType: '',
      tempSelectedProductCategory: '',
      tempSelectedProductName: '',
      currentCategoryLevel: 'type'
    });
    this.loadCategoryList();
  },

  // 应用分类筛选
  applyCategoryFilter() {
    const { tempSelectedType, tempSelectedProductCategory, tempSelectedProductName } = this.data;
    
    // 生成显示文本
    const categoryText = this.generateCategoryText(tempSelectedType, tempSelectedProductCategory, tempSelectedProductName);
    
    this.setData({
      selectedType: tempSelectedType,
      selectedProductCategory: tempSelectedProductCategory,
      selectedProductName: tempSelectedProductName,
      selectedCategoryText: categoryText
    });
    
    this.loadSearchResults(true);
    this.hideCategoryModal();
    console.log('按分类筛选:', tempSelectedType, tempSelectedProductCategory, tempSelectedProductName);
  },


  // 下拉刷新
  onPullDownRefresh() {
    this.loadSearchResults(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSearchResults();
    }
  },

  // 跳转到详情页
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    
    console.log('跳转到详情页:', { id, type });
    
    let pagePath = '';
    switch (type) {
      case 'group':
        pagePath = PAGE_GROUP_DETAIL;
        break;
      case 'demand':
        pagePath = PAGE_DEMAND_DETAIL;
        break;
      case 'processing':
        pagePath = PAGE_PRODUCT_DETAIL;
        break;
      case 'material':
        pagePath = PAGE_PRODUCT_DETAIL;
        break;
      case 'inventory':
        pagePath = PAGE_BULK_MATERIAL_DETAIL;
        break;
      default:
        pagePath = PAGE_PRODUCT_DETAIL;
    }
    
    goToPage(pagePath, { id });
  }
});
